# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://47.94.58.53/AliPay/JcSaoMaPayServlet'
_QUERY_GATEWAY = 'http://47.94.58.53/AliPay/AliMD5OrderQueryServlet'

APP_CONF = {
    'hcyd001': {
        'API_KEY': '16703d2989026dd890337a2a999c9267',
        'gateway': 'http://47.94.58.53/AliPay/JcSaoMaPayServlet',
        'query_gateway': 'http://47.94.58.53/AliPay/AliMD5OrderQueryServlet',

    },
    'bsjy001': {
        'API_KEY': 'c941c435e418c319b464b4b44ec7151f',
        'gateway': 'http://47.94.58.53/QPay/JcQPayServlet',
        'query_gateway': 'http://47.94.58.53/QPay/QOrderQueryServlet',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = 'area={}&area_out_trade_no={}&subject={}&total_fee={}&key={}'.format(
        parameter['area'],
        parameter['area_out_trade_no'],
        parameter['subject'],
        parameter['total_fee'],
        key,
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_query_sign(parameter, key):
    s = 'area={}&area_out_trade_no={}&key={}'.format(
        parameter['area'],
        parameter['area_out_trade_no'],
        key,
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def gen_notify_sign(parameter, key):
    s = 'area_out_trade_no={}&gmt_payment={}&total_fee={}&trade_no={}&trade_status={}&key={}'.format(
        parameter['area_out_trade_no'],
        parameter['gmt_payment'],
        parameter['total_fee'],
        parameter['trade_no'],
        parameter['trade_status'],
        key,
    )
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = gen_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("jcpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('area', app_id),
        ('area_notify_url', '{}/pay/api/{}/jcpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('area_out_trade_no', str(pay.id)),
        ('subject', 'htc'),
        ('total_fee', str(pay_amount)),
        ('is_jump', '0'),
        ('body', 'kkk'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("jcpay create charge data: %s %s",
                 response.status_code, response.text)
    res_obj = json.loads(response.text)
    charge_resp.update({
        'charge_info': res_obj['code_url'].decode('gbk'),
    })
    return charge_resp


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("jcpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['area_out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('jcpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['trade_status']
    trade_no = data['trade_no']
    total_fee = float(data['total_fee'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS':
        _LOGGER.info('jcpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)

    parameter_dict = {}
    parameter_dict['area'] = app_id
    parameter_dict['area_out_trade_no'] = str(pay_id)
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    if response.status_code == 200:
        # response text is a pure html text
        data = json.loads(response.text)
        _LOGGER.info('jcpay response.text :%s', response.text)
        trade_status = data['code']
        trade_no = ''
        total_fee = float(pay_order.total_fee)

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '1':
            _LOGGER.info('jcpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('jcpay data error, status_code: %s', response.status_code)
